<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    label-position="top"
  >
    <el-form-item label="账号" prop="username">
      <el-input
        clearable
        v-model="ruleForm.username"
        type="text"
        autocomplete="off"
      >
        <template #prefix>
          <el-icon><User /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item label="密码" prop="pass">
      <el-input
        clearable
        v-model="ruleForm.pass"
        type="password"
        autocomplete="off"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item class="btns">
      <el-button type="primary" @click="submitForm($refs.ruleFormRef)"
        >登录</el-button
      >
      <el-button @click="resetForm($refs.ruleFormRef)">重置</el-button>
      <el-button @click="openRegister">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { login, getuserinfo } from '@/api/user.js';
import { Lock, User } from '@element-plus/icons-vue';

export default {
  components: {
    Lock,
    User,
  },
  data() {
    return {
      ruleForm: {
        pass: '',
        username: '',
      },
      rules: {
        pass: [
          { required: true, validator: this.validatePass, trigger: 'blur' },
        ],
        username: [{ required: true, message: '请输入账号！' }],
      },
    };
  },
  methods: {
    // 校验密码
    validatePass(rule, value, callback) {
      if (value.trim() === '') {
        callback(new Error('请输入密码！'));
      } else {
        if (!this.$refs.ruleFormRef) return;
        callback();
      }
    },
    // 登录按钮
    submitForm(formEl) {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          login({
            username: this.ruleForm.username,
            password: this.ruleForm.pass,
          }).then((res) => {
            console.log(res);
            if (res.code === 1) {
              getuserinfo(res.user.id).then((res1) => {
                this.$store.commit('updateUserInfo', res1.info);
              });
              this.$router.push('/');
            }
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    // 重置按钮
    resetForm(formEl) {
      if (!formEl) return;
      formEl.resetFields();
    },

    // 点击注册按钮
    openRegister() {
      this.$router.push({ name: 'register' });
    },
  },
};
</script>

<style lang="scss" scoped>
.loginpage {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>
